/* ************************************************************************
> File Name:     hashtable.c
> Author:        zhfu
> mail:          3346897597@qq.com
> Created Time:  2022年05月04日 星期三 22时02分02秒
> Description:   
 ************************************************************************/
#include<stdlib.h>
#include"hashtable.h"
#include"intlist.h"

link search(my_hash *h, int v)
{
   if (!h->p){
       return NULL;
   }

   if (!(h->p)[(h->my_hashfunc)(v)]){
       return NULL;
   }

   intlist l = {(h->p)[(h->my_hashfunc)(v)]};
   return list_search(&l, v);
}


void insert(my_hash *h, int v)
{
    if (!h->p){
        h->p = malloc(h->len * sizeof (h->p) );
        int i;
        for (i = 0; i < h->len; ++i){
            (h->p)[i] = NULL;
        }
        return;
    }

    int index = (h->my_hashfunc)(v);
    if (!(h->p)[index]){
        intlist l = {NULL};
        list_insert(&l, v);
        (h->p)[index] = l.head;
        return;
    }

    intlist l = {(h->p)[index]};
    list_insert(&l, v);
    (h->p)[index] = l.head;

    return;
}

void delete(my_hash *h, int v)
{
    if (search(h, v)){
        int index = (h->my_hashfunc)(v);
        intlist l = {(h->p)[index]};
        list_delete(&l, v);
        (h->p)[index] = l.head;
    }
}

void print_hash(my_hash h)
{
    int i;
    for (i = 0; i < h.len; ++i){
        intlist l = {(h.p)[i]};
        print_list(&l);
    }
}

void free_hash(my_hash *h)
{
    int i;
    for (i = 0; i < h->len; ++i){
        intlist l = {(h->p)[i]};
        free_list(&l);
    }
}
